package com.xuecheng.manage_media_process.mq;

import com.alibaba.fastjson.JSON;
import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.MediaFileProcess_m3u8;
import com.xuecheng.framework.utils.HlsVideoUtil;
import com.xuecheng.framework.utils.Mp4VideoUtil;
import com.xuecheng.manage_media_process.config.RabbitMQConfig;
import com.xuecheng.manage_media_process.dao.MediaFileRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Component
public class MediaProcessTask {

    //上传文件根目录
    @Value("${xc-service-manage-media.video-location}")
   public String serverPath;
    //ffmpeg绝对路径
   @Value("${xc-service-manage-media.ffmpeg-path}")
   public String ffmpeg_path;
    @Autowired
    MediaFileRepository mediaFileRepository;

    private static final Logger LOGGER = LoggerFactory.getLogger(MediaProcessTask.class);

    @RabbitListener(queues = RabbitMQConfig.EX_MEDIA_QUEUE,containerFactory = "customContainerFactory")
    public void receiveMediaProcessTask(String msg){
        //接受消息，拿到mediaId
      Map map=  JSON.parseObject(msg, Map.class);
      LOGGER.info("receive media process task msg :{} ",map);
      String mediaId= (String) map.get("mediaId");
        //从数据库中找到文件信息进行处理
        Optional<MediaFile> optional=mediaFileRepository.findById(mediaId);
        if(!optional.isPresent()){
           return;
        }
        MediaFile mediaFile=optional.get();

        //判断文件类型
        String  fileType=mediaFile.getFileType();
        if(fileType==null||!fileType.equals("avi")){
            mediaFile.setProcessStatus("303004");//修改状态 无需处理
            mediaFileRepository.save(mediaFile);
            return;
        }else {
            mediaFile.setProcessStatus("303001");//修改状态 处理中
            mediaFileRepository.save(mediaFile);
        }
        //将avi文件转成mp4
        String video_path=serverPath+mediaFile.getFilePath()+mediaFile.getFileName();
        String mp4_name=mediaFile.getFileId()+".mp4";
        String mp4folder_path = serverPath + mediaFile.getFilePath();
        //参数String ffmpeg_path, String video_path, String mp4_name, String mp4folder_path
        Mp4VideoUtil videoUtil=new Mp4VideoUtil(ffmpeg_path,video_path,mp4_name,mp4folder_path);
        String result=videoUtil.generateMp4();
        //判断结果进行处理
        if (result==null||!result.equals("success")){
            mediaFile.setProcessStatus("303003");//修改状态 处理失败
            MediaFileProcess_m3u8 mediaFileProcess_m3u8=new MediaFileProcess_m3u8();
            mediaFileProcess_m3u8.setErrormsg(result);
            mediaFileRepository.save(mediaFile);
            return;
        }
        //将mp4文件换成m3u8和ts
        String mp4_video_path=serverPath+mediaFile.getFilePath()+mp4_name;
        String m3u8_name=mediaFile.getFileId()+".m3u8";
        String m3u8folder_path=serverPath+mediaFile.getFilePath()+"hls/";
        HlsVideoUtil hlsVideoUtil=new HlsVideoUtil(ffmpeg_path,mp4_video_path,m3u8_name,m3u8folder_path);
       String tsResult= hlsVideoUtil.generateM3u8();
       if(tsResult==null||!tsResult.equals("success")){
           //操作失败写入处理日志
           mediaFile.setProcessStatus("303003");//处理状态为处理失败
           MediaFileProcess_m3u8 mediaFileProcess_m3u8 = new MediaFileProcess_m3u8();
           mediaFileProcess_m3u8.setErrormsg(result);
           mediaFile.setMediaFileProcess_m3u8(mediaFileProcess_m3u8);
           mediaFileRepository.save(mediaFile);
           return ;
       }
       //处理成功
     List<String> ts_list= hlsVideoUtil.get_ts_list();
       mediaFile.setProcessStatus("303002"); //处理成功状态
        MediaFileProcess_m3u8 mediaFileProcess_m3u8=new MediaFileProcess_m3u8();
        mediaFileProcess_m3u8.setTslist(ts_list);
        mediaFile.setMediaFileProcess_m3u8(mediaFileProcess_m3u8);
      //保存m3u8文件url
        mediaFile.setFileUrl(mediaFile.getFilePath()+"hls/"+m3u8_name);
        mediaFileRepository.save(mediaFile);
    }

}
